package cn.waqwb.service.impl;

import cn.waqwb.entity.Book;
import cn.waqwb.service.BookService;
import cn.waqwb.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * @author JokerQ
 * @date 2020/7/30 - 21:50
 */
public class BookServiceImpl implements BookService {
    @Override
    public ArrayList getBooks() {
        ArrayList books = null;
        try {
            Connection con = DBUtil.getConnection();
            String sql = "select * from t_book";
            PreparedStatement prep = con.prepareStatement(sql);
            ResultSet rs = prep.executeQuery();
            books = new ArrayList();
            while (rs.next()) {
                Book book = new Book();
                book.setId(rs.getInt("id"));
                book.setProductName(rs.getString("product_name"));
                book.setFixedPrice(rs.getDouble("fixed_price"));
                book.setDangPrice(rs.getDouble("dang_price"));
                book.setProductPic(rs.getString("product_pic"));
                book.setAuthor(rs.getString("author"));
                book.setPublishing(rs.getString("publishing"));
                book.setPublishTime(rs.getString("publish_time"));
                book.setAuthorSummary(rs.getString("author_summary"));
                book.setDescription(rs.getString("description"));
                book.setScore(rs.getInt("score"));
                books.add(book);
            }
            DBUtil.close(rs, prep, con);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return books;
    }

    @Override
    public Book getBookById(int id) {
        Book book=null;
        try {
            Connection con= DBUtil.getConnection();
            String sql="select * from t_book where id=?";
            PreparedStatement prep=con.prepareStatement(sql);
            prep.setInt(1, id);
            ResultSet rs=prep.executeQuery();
            if(rs.next()){
                book=new Book();
                book.setId(rs.getInt("id"));
                book.setProductName(rs.getString("product_name"));
                book.setFixedPrice(rs.getDouble("fixed_price"));
                book.setDangPrice(rs.getDouble("dang_price"));
                book.setProductPic(rs.getString("product_pic"));
                book.setAuthor(rs.getString("author"));
                book.setPublishing(rs.getString("publishing"));
                book.setPublishTime(rs.getString("publish_time"));
                book.setAuthorSummary(rs.getString("author_summary"));
                book.setDescription(rs.getString("description"));
                book.setScore(rs.getInt("score"));
            }
            DBUtil.close(rs, prep, con);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return book;
    }
}
